<template>
  <div id="roleEdit" >
    <Modal v-model="modal.show" :loading="modal.loading" :title="modal.title" width="700px" :mask-closable="false" :footer-hide=true :closable="false">
      <Form ref="formRole" :model="rowData" label-position="right" :label-width="80" :rules="rules">
        <FormItem :label="$t('role')"><Input v-model="rowData.code" :readonly="modal.readonly" prop="code" maxlength=20></Input></FormItem>
        <FormItem :label="$t('name')"><Input v-model="rowData.name" :readonly="modal.readonly" prop="name" maxlength=50></Input></FormItem>
        <FormItem :label="$t('data_permission')">
          <Select v-model="rowData.roleLevel" style="width:200px" :readonly="modal.readonly">
            <Option v-for="item in roleLevelList" :value="item.value" :key="item.value">{{ item.label }}</Option>
          </Select>
        </FormItem>
        <FormItem :label="$t('permission')">
          <Button @click="auth" v-show="modal.action!='ADD'">{{$t('authorization')}}</Button>
        </FormItem>
        <FormItem :label="$t('permission')" v-show="false">

          <Transfer
            :data="permissionData"
            :target-keys="targetKeys"
            :titles="transferTitles"
            filterable
            :filter-method="filterMethod"
            @on-change="handleChange"></Transfer>
        </FormItem>
        <FormItem>
          <div style="float: right;">
            <Button v-show="modal.action!='VIEW'" type="primary"  @click="save" >{{$t('save')}}</Button>
            <Button @click="close">{{$t('cancel')}}</Button>
          </div>
        </FormItem>
      </Form>
    </Modal>
    <RoleAuthorization ref="roleAuthorization"></RoleAuthorization>
  </div>
</template>
<script>
import {allpermission,permissionbyuser} from '@/api/permission';
import {queryByRole} from '@/api/RolePermission';
import Role from '@/api/role';
import RoleAuthorization from "@/view/User/RoleAuthorization";
import {apiResult} from "@/libs/util";
export default {
  name:"roleEdit",
  components:{RoleAuthorization},
  computed:{
    roleLevelList(){
      return[{value: 1, label: this.$t('permission_level_1')},
        {value: 2, label: this.$t('permission_level_2')},
        {value: 3, label: this.$t('permission_level_3')},
        {value: 4, label: this.$t('permission_level_4')}]
    },
    rules(){
        return{
          code:[{required: true, message: this.$t('role_must_be_enter'), trigger: 'blur'}],
          name:[{required: true, message: this.$t('name_must_be_enter'), trigger: 'blur'}]
        }
    }
  },
  data(){
    return{
      roleApi: new Role(),
      modal:{
        show:false,
        loading:false,
        readonly:false,
        title:"",
        action:"VIEW",
        callback:null
      },
      rowData:{
        code:null,
        name:null,
        roleLevel:null
      },

      transferTitles: [],
      /** 可选的所有权限 数据格式｛Key:xxx,label:xxx｝*/
      permissionData: [],//this.getMockData(),
      /** 选择的权限  只有key 如[1]*/
      targetKeys: [],//this.getTargetKeys(),

    }
  },
  methods:{
    auth(){
      this.$refs.roleAuthorization.openDialog(this.rowData.id,this.modal.action);
    },
    openDialog: function (action,row, callback) {
      this.modal.show=true;
      this.modal.readonly=false;
      this.modal.callback = callback;
      this.modal.action = action;

      if (action=="ADD"){
        this.modal.title=this.$t('add');
        this.$refs["formRole"].resetFields();
      }else if (action=="VIEW"){
        this.modal.title=this.$t('browse');
        this.$refs["formRole"].resetFields();
        this.modal.readonly=true;
      }else if (action=="EDIT"){
        this.modal.title=this.$t('edit');
      }
      if (row != null) {
        this.rowData = row;
      }
      /** 查询权限数据 */
      //this.getRoleData();
      this.getAllPermission();
      this.findPermissionByRole(this.rowData)
    },

    getAllPermission(){
      /** 取得所有权限 */
      allpermission().then(res=>{
        apiResult(res.data,false,result=>{
          let p = null;
          this.permissionData = [];
          for(let i in result.data){
            p=result.data[i];
            if (this.modal.action == "VIEW"){
              this.permissionData.push({key:p.id,label:p.pmName,description:p.pmName,disabled:true});
            }else{
              this.permissionData.push({key:p.id,label:p.pmName,description:p.pmName,disabled:false});
            }

          }
        });

      })
    },
    /** 权限选中 */
    handleChange(newTargetKeys) {
      this.targetKeys = newTargetKeys;
    },
    /** 权限搜索*/
    filterMethod(data, query) {
      return data.label.indexOf(query) > -1;
    },
    save(){
      let that = this;
      this.$refs["formRole"].validate((valid) => {
          if (that.modal.action == "VIEW"){that.close();}
          if (valid) {
            that.rowData.permissions=[];
            if (!!that.targetKeys){
              for(let i in that.targetKeys){
                if (i<that.targetKeys.length){
                  /** 最后一项数据不对，此处忽略 */
                  that.rowData.permissions.push({id:that.targetKeys[i]});
                }
              }
            }
            /** 新增 */
            if (that.rowData.id == null){
              this.roleApi.add(JSON.stringify(that.rowData)).then(res => {
                apiResult(res.data,true,result=>{
                  if (!!that.modal.callback) that.modal.callback();
                  that.close();
                })
              })
            }else{
              /** 修改 */
              this.roleApi.update(JSON.stringify(that.rowData)).then(res => {
                apiResult(res.data,true,result=>{
                  if (!!that.modal.callback) that.modal.callback();
                  that.close();
                })
              })
            }
          }
      })

    },

    close(){
      this.modal.show=false;
      this.$refs["formRole"].resetFields();
    },

    /** 当前角色 已有的权限 */
    findPermissionByRole(row){
      queryByRole(JSON.stringify({roleId:row.id})).then(res=>{
        //console.log(res);
        apiResult(res.data,false,result=>{
          //console.log(result.data);
          let p = null;
          this.targetKeys = [];
          for(let i in result.data){
            p=result.data[i];
            this.targetKeys.push(p.permissionId);
          }
        })
      })
    },
  },
  mounted() {
    this.transferTitles=[this.$t('all_permissions'), this.$t('selected_permissions')];
  }

}
</script>
<style>

</style>
